<?php
include("prepend.inc.php");
include_once('GetContacts.php');
include_once 'ThirdParty/GContacts.php';

/*
 * A generic implementation of Contacts being imported
 * Currently only GMail contacts has been embedded
 */
class ImportContacts extends QForm
{
	
	protected $rdbContactSource;
	protected $txtUser;
	protected $txtPassword;	
	protected $btnGetContacts;
	
	
	protected function Form_Run()
	{
		QApplication::CheckRemoteAdmin();
		QApplication::$LoadedPage = 'Import Contacts';
	}
	
	protected function Form_Create()
	{
		$this->rdbContactSource_Create();
		$this->txtUser_Create();
		$this->txtPassword_Create();
		$this->btnGetContacts_Create();
	}
	
	protected function rdbContactSource_Create()
	{
		$this->rdbContactSource = new QRadioButtonList($this);
		$this->rdbContactSource->AddItem(new QListItem('GMail','G',true));
		$this->rdbContactSource->AddItem(new QListItem('Yahoo','Y',false));
		$this->rdbContactSource->AddItem(new QListItem('Hotmail','H',false));
		$this->rdbContactSource->RepeatDirection = QRepeatDirection::Horizontal;
		$this->rdbContactSource->RepeatColumns = 3;	
	}
	
	protected function txtUser_Create()
	{
		$this->txtUser = new QTextBox($this);
		$this->txtUser->Name = 'Email ID';
	}
	
	protected function txtPassword_Create()
	{
		$this->txtPassword = new QTextBox($this);
		$this->txtPassword->Name = 'Password';
		$this->txtPassword->TextMode = QTextMode::Password;
		$this->txtPassword->AddAction(new QEnterKeyEvent(),new QServerAction('getContacts'));
	}
	
	protected function btnGetContacts_Create()
	{
		$this->btnGetContacts = new QButton($this);
		$this->btnGetContacts->Name = 'Get Contacts';
		$this->btnGetContacts->AddAction(new QClickEvent(),$this->getContacts());	
	}
	
	protected function getContacts()
	{
		switch ($this->rdbContactSource->SelectedValue)
		{
			case 'G':
				$this->getGoogleContacts();
				break;
				
			case 'Y':
				break;
				
			case 'H':
				break;
				
			 default:
				break;
				
		}
	}
	
	protected function getGoogleContacts()
	{
		$objContacts = new GetContacts();
		$arrContacts = $objContacts->GetGContacts($this->txtUser,$this->txtPassword);
		$contactCount = sizeof($arrContacts);

		foreach($arrContacts as $person)
		{
			$count = Peopledetails::QueryCount(QQ::Equal(QQN::Peopledetails()->Email,$person['contactMail']));
			if($count <> 0)
			{
				$objPerson = Peopledetails::QuerySingle(QQ::Equal(QQN::Peopledetails()->Email,$person['contactMail']));
			}
			else
			{
				$objPerson = new Peopledetails();
			}
		
			$objPerson->FullName = $person['contactName'];
			$objPerson->Phone = $person['contactPhone'];
			$objPerson->Address = $person['contactAddr'];
			$objPerson->Email = $person['contactMail'];
		
			$objPerson->Save();
				
		}
		QApplication::DisplayAlert('Successfully imported ' . $contactCount . 'contacts from Google Contacts');
	}
	
	
	
	
}

ImportContacts::Run('ImportContacts');
?>

